﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Mojito.Model;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace Mojito.Filters
{
    public class ExceptionFilter : IExceptionFilter
    {
        private static NLog.Logger _Logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        ///  错误捕获
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            var exception = context.Exception;
            var message = context.Exception.Message;
            var json = new ResponseModel()
            {
                Message = message
            };
            // 应用程序错误
            if (exception is ApplicationException)
            {
                json.Code = ResponseModelCode.AppError;
                _Logger.Warn(
                  exception,
                  exception.Message);
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
            }
            // 系统错误
            else
            {
                json.Message = "系统错误, 请查看日志";
                json.Code = ResponseModelCode.SystemError;
                _Logger.Error(
                      exception,
                      exception.Message);
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
            }
            context.Result = new JsonResult(json);
            // 标记错误已处理
            context.ExceptionHandled = true;
        }
    }
}
